<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/jquery-3.3.1.js" type="text/javascript"></script>
</head>
<body>
<div>
    <input type="text" class="user-name" />
        <input type="button" class="btn-connect" value="连接" />
    </div>
    <div>
        <input type="text" class="msg" />
        <input type="button" class="btn-msg" value="发送" />
    </div>
</body>
<script type="text/javascript">
    var userInfo = {}
    var ws = null

    //连接服务器
    $('.btn-connect').click(function () {
        var userName = $('.user-name').val()
        if (userName == null || userName == '') {
            alert('请输入用户名')
            return
        }
        connectServer(userName)
    })

    //发送信息
    $('.btn-msg').click(function () {
        if (!ws) {
            alert("未连接服务器")
            return
        }

        if (!userInfo.userKey) {
            alert("未初始化用户信息")
            return
        }

        var msg = $('.msg').val()
        if (!msg) {
            alert("请输入消息")
            return
        }

        sendMessage(ws, msg)
    })

    function connectServer(userName) {
        if (window.WebSocket) {
            ws = new WebSocket('ws://127.0.0.1:8001?userName=' + userName)

            ws.onmessage = function(e) {
                try {
                    var data = JSON.parse(e.data)
                    progressMsg(data)
                }catch (e) {
                    console.log("解析数据失败", e)
                }

            }

            ws.onopen = function () {
                console.log('连接成功')
            }

            ws.onclose = function () {
                console.log('连接关闭')
                resetInfo()
            }

            ws.onerror = function () {
                console.log('发生错误')
                resetInfo()
            }
        } else {
            alert("抱歉，您的浏览器不支持webSocket！")
        }
    }
    
    //重置信息
    function resetInfo() {
        ws = null
        userInfo = {}
    }

    //发送消息
    function sendMessage(ws, msg) {
        data = {
            command: 'message',
            msg: msg
        }
        data = progressSendMsg(data)
        ws.send(data)
    }

    //处理要发送的消息
    function progressSendMsg(msg) {
        if (typeof msg != 'string') {
            msg = JSON.stringify(msg)
        }
        return msg
    }

    //处理接收的消息
    function progressMsg(data) {
        //命令
        var command = data.command
        switch (command) {
            //用户进入
            case "userInto":
                userInto(data.userKey, data.msg)
                break
            //返回用户信息
            case "returnUserInfo":
                initUserInfo(data.userKey, data.userName)
                break
            //其他用户发送消息
            case "message":
                receivePlainText(data.userKey, data.userName, data.msg)
                break
            default:
                console.log('未知命令：', command)
                break
        }
    }

    //初始化个人信息
    function initUserInfo(userKey, userName) {
        userInfo = {
            userKey,
            userName
        }
    }

    //新用户进入
    function userInto(userKey, msg) {
        if (!userInfo.userKey) {
            console.log("无效userKey：", userInfo.userKey)
            return
        }

        //新进入的用户是自己
        if (userInfo.userKey == userKey) {
            console.log("您加入聊天")
        } else {
            console.log(msg)
        }
    }

    //接收用户发送的普通文本
    function receivePlainText(userKey, userName, msg) {
        //发送消息的是自己
        if (userInfo.userKey == userKey) {
            console.log('我说：' + msg)
        } else {
            console.log(userName + ' 说：' + msg)
        }
    }
</script>
</html>